// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// S [author] rhyme_lph
// F [email]  rhymelph@gmail.com
// S [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/src/entities/debit_note_detail_entity.dart';
import 'package:finance_app/src/http_service/http_debit_note_service.dart';
import 'package:finance_app/src/mixin/search_data_list_mixin.dart';
import 'package:finance_app/src/widgets/bottom_sheet/delete_info_bottom_sheet.dart';
import 'package:finance_app/src/widgets/bottom_sheet/got_it_tip_bottom_sheet.dart';
import 'package:flutter/material.dart';

class DeleteDebitNoteProvider extends BaseProvider<List<DebitNoteDetailEntity>>
    with SearchDataListMixin<List<DebitNoteDetailEntity>> {
  List<DebitNoteDetailEntity> currentSelectList = [];

  @override
  Future get dataFuture => HttpDebitNoteService.debitNoteList(
        status: ['open'],
      );

  void onSelect(DebitNoteDetailEntity value) {
    if (currentSelectList.contains(value)) {
      currentSelectList.remove(value);
    } else {
      currentSelectList.add(value);
    }
    update();
  }

  void onCancel() {
    obtainContext?.call((context) {
      Navigator.of(context).pop();
    });
  }

  void onDelete() {
    if (currentSelectList.length == 0) {
      showToast(S.current.please_select_debit_note);
      return;
    }
    obtainContext?.call((context) async {
      bool isSuccess = await showDeleteDebitNoteInfoBottomSheet(context);
      if (isSuccess == true) {
        isSuccess = false;
        await post(
            HttpDebitNoteService.deleteDebitNotes(
                currentSelectList.map((e) => e.id).toList()),
            loadingTip: S.current.loading,
            autoHandler: AutoHandler.Toast, onSuccess: (result) {
          isSuccess = true;
        });
        if (isSuccess) {
          await showDeleteDebitNoteSuccessBottomSheet(context);
          Navigator.of(context).pop({
            'delete': true,
          });
        }
      }
    });
  }

  @override
  void searchRefreshData(data) {}
}
